import 'dart:math';

import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:ymt/api/apis.dart';
import 'package:ymt/db/offline_database_provider.dart';
import 'package:ymt/db/user_database_provider.dart';
import 'package:ymt/model/product.dart';
import 'package:ymt/model/product/detail.dart';
import 'package:ymt/model/product/variant.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:ymt/ui/recommend_products.dart';
import 'package:ymt/ui/video_player.dart';
import 'package:ymt/utils/request.dart';

class Screen extends StatefulWidget{

  final Product product;
  _ScreenState _screenState;
  ProductDetail productDetail;
  var dismiss;
  final _pageContext;
  Screen(this._pageContext, this.product, this.productDetail, this.dismiss);

  @override
  State<StatefulWidget> createState() {
    _screenState = _ScreenState(_pageContext, product, productDetail, dismiss);
    return _screenState;
  }
}

class _ScreenState extends State<Screen>{

  List<Variant> _variants;
  final Product product;
  FavProduct favProduct;
  ProductDetail productDetail;
  bool isFavorite = false;
  UserDatabaseProvider userDatabaseProvider;

  Dio dio;
  var dismiss;

  var _pageContext;

  _ScreenState(this._pageContext, this.product, this.productDetail, this.dismiss);

  @override
  void initState() {
    initData();
    initDio();
    executeTask();
    super.initState();
  }

  initData(){
    favProduct = FavProduct();
    favProduct.id = product.id;
    favProduct.name = product.name;
    favProduct.thumb_picture = product.main_picture;
    favProduct.main_picture = product.main_picture_big;
  }

  executeTask() async {
    _queryProductIsFavorite(product.id);

    var connectivityResult = await Connectivity().checkConnectivity();
    print(connectivityResult);
    initDio();
    if (connectivityResult == ConnectivityResult.none) {
      _loadOffline = true;
    }else{
      _loadOffline = false;
    }
    _requestProduct(product.id);
  }

  @override
  Widget build(BuildContext context) {
    var topButton = Container(child: _buildTopButtons(_pageContext),margin: EdgeInsets.only(top: 40, bottom: 15),alignment: Alignment.topCenter,);
    var centerArea = Align(child: _buildSizedBox(_buildPriceList()), alignment: Alignment.center,);
    var qrCodeArea =  _buildQrcodeImage(productDetail != null ? productDetail.qrcode : "");

    var content = Column(children: <Widget>[topButton, Expanded(child: Stack(children: <Widget>[centerArea, qrCodeArea],),)],);

    return new MaterialApp(
      theme: ThemeData(backgroundColor: Colors.transparent, scaffoldBackgroundColor: Colors.transparent),
      home: new Scaffold(
        body: content,
      ),
    );
  }

  Widget _buildVertical(){
    return Column(children: <Widget>[],);
  }

  Widget _buildStack(List<Widget> widgets){
    return Stack(children: widgets,);
  }

  Widget _buildTopButtons(context){

    List<Widget> buttons = List();
    buttons.add(buildClickItem(buildButtonColumn(isFavorite ? Icons.favorite : Icons.favorite_border,isFavorite ? "已收藏" : "收藏"), _onFavoriteClick));
    String videoLabel = "视频";
    String url ="http://image.nnccnn.cn/public-retailer-default.mp4";
    if (productDetail != null && productDetail.video != null) {
      url = productDetail.video;
      if(url != null){
        if (url.contains("company")) {
          videoLabel = "企业介绍";
        } else if (url.contains("product")) {
          videoLabel = "产品介绍";
        }
        buttons.add(buildClickItem(buildButtonColumn(Icons.play_circle_filled, videoLabel), () =>{
          Navigator.push(context, MaterialPageRoute(builder: (context) =>  VideoPlayerPager(url),))
        }));
      }
    }
    buttons.add(buildClickItem(buildButtonColumn(Icons.all_inclusive,"同品牌推荐"),()=>{
      Navigator.push(context, MaterialPageRoute(builder: (context) =>  RecommendProductsPage(product.id),))
    }));
    buttons.add(buildClickItem(buildButtonColumn(Icons.ondemand_video,"自动轮播"),()=>{
      dismiss()
    }));
    return Row(children: buttons, mainAxisAlignment: MainAxisAlignment.center,);
  }

   buildClickItem(child, onTap) {
    return click(
        Container(child: child, margin: EdgeInsets.only(left: 20, right: 20),),
        onTap);
  }

  Widget click(child, onTap) {
    return GestureDetector(child: child, onTap: onTap,);
  }

  Column buildButtonColumn(IconData icon, String label) {
    Color color = Colors.white;
    return new Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        new Icon(icon, color: color),
        new Container(
          margin: const EdgeInsets.only(top: 8.0),
          child: new Text(
            label,
            style: new TextStyle(
              fontSize: 12.0,
              fontWeight: FontWeight.w400,
              color: color,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPriceList(){
    return ListView.builder(itemBuilder: (context, position){
      if (_variants != null && position <= _variants.length - 1) {
        return _buildRow(_variants[position]);
      }
    }, physics: BouncingScrollPhysics(),);
  }

  Widget _buildSizedBox(widget) {
    return Container(
      width: MediaQuery
          .of(_pageContext)
          .size
          .width / 2,
      height: MediaQuery
          .of(_pageContext)
          .size
          .height / 1.5,
      child: widget,
      margin: EdgeInsets.only(bottom: 15),
      decoration: BoxDecoration(color: Color.fromARGB(102, 102, 102, 102)),);
  }

  Widget _buildQrcodeImage(String content) {
    if (content == null || content.isEmpty) {
      return Container();
    }
    Widget qrcode = new QrImage(data: content,
      size: 130,
      version: QrVersions.auto,
      backgroundColor: Colors.white,);
    print(content);
    Align right = Align(child: qrcode, alignment: Alignment.bottomRight,);
    return Container(child: right, margin: EdgeInsets.all(30),);
  }


  Widget _buildRow(Variant variant) {
    return new ListTile(
      title: new Text(
        variant.name,style: TextStyle(color: Colors.white),
      ),
      trailing: Text("￥${variant.value}", style: TextStyle(color: Colors.white),),
    );
  }

  Future<bool> _queryProductIsFavorite(productId) async {
    //查询当前产品是否被收藏
    // Get a location using getDatabasesPath
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'user.db');
    userDatabaseProvider = UserDatabaseProvider();
    await userDatabaseProvider.open(path);
    List<FavProduct> allFavorite = await userDatabaseProvider.all();
    for (FavProduct product in allFavorite) {
      if (productId == product.id) {
        setState(() {
          isFavorite = true;
        });
        break;
      }
    }
  }

  _onFavoriteClick() async {
    if(isFavorite){
      int result= await userDatabaseProvider.delete(product.id);
      print("删除 $result");
    }else{
      int result= await userDatabaseProvider.insert(favProduct);
      print("收藏 $result");
    }
    setState(() {
      if(isFavorite){
        isFavorite = false;
      }else{
        isFavorite = true;
      }
    });
  }

  bool _loadOffline = false;

  _requestProduct(id) async {
    if(_loadOffline){
      await OfflineDatabaseProvider().open((Database database) async {
        List<Map> maps = await database.query(OfflineDatabaseProvider.TABLE_VARIANTS, where: "product_id = ?", whereArgs: [product.id], orderBy: "price DESC");
        if (mounted) {
          setState(() {
            _variants = maps.map((e) => Variant.fromDatabase(e, product.retail_rate)).toList();
          });
        }
      });
    }else {
      Response response = await dio.get(ApiPaths.VARIANTS, queryParameters: {"id": product.id});
      if (mounted) {
        setState(() {
          _variants = List<Variant>.from(
              response.data.map((e) => Variant.fromJson(e)).toList());
        });
      }
    }
  }

  void initDio(){
    dio = Request.dio();
  }
}